package org.java.json;

import org.codehaus.jackson.map.ObjectMapper;
import org.java.bean.Birthday;
import org.java.bean.User;

import java.io.IOException;

/**
 * Jackson
 * Created by Administrator on 2016/12/27.
 */
public class JacksonTest {
    public static void main(String[] args) throws IOException {
        // 测试对象转换为json字符串
        //System.out.println(obj2json());
        // 测试字符串转对象
        json2Object();
    }

    /**
     * 测试对象转换为json字符串
     * */
    public static String obj2json(){
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = "";
        try {
            jsonStr = mapper.writeValueAsString(new User());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonStr;
    }

    /**
     * 测试json转对象
     * */
    public static void json2Object() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Birthday bj = new Birthday();
        bj.setBirthday("111");

        String json2 = mapper.writeValueAsString(bj);
        System.out.println("The JSON from Class is: " + json2);

        Birthday bj2 = mapper.readValue(json2, Birthday.class);
        System.out.println(bj2.getBirthday());
    }
}
